import { NavigationProp, RouteProp } from '@react-navigation/native';
import React, { useEffect, useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet, TouchableOpacity } from 'react-native';
import { Button, Divider, Text, View } from 'native-base';
import AntDesign from 'react-native-vector-icons/AntDesign';
import UserRequest from '../../../request/userRequest.ts';
import { CommonStyle } from '../../../common/commonStyle.ts';
import Empty from '../../../component/Empty.tsx';
import { useBoolean } from 'ahooks';
import LoadingSkeleton from '../../../component/LoadingSkeleton.tsx';
import to from '../../../utils/to.ts';
import Tools from '../../../utils/Tools.ts';

interface IReceivingAddressProps {
  navigation: NavigationProp<any, 'receivingAddress'>;
  route: RouteProp<any, 'receivingAddress'>;
}

const ReceivingAddress: React.FC<IReceivingAddressProps> = ({ navigation, route }) => {
  const [list, setList] = useState<IListShippingAddressesRes[]>([]);
  const [loading, { setTrue, setFalse }] = useBoolean(true);

  useEffect(() => {
    fetchListShippingAddresses().then();
  }, []);

  useEffect(() => {
    if (route.params?.refresh) {
      setList([]);
      fetchListShippingAddresses().then();
    }
  }, [route.params]);

  /**
   * 请求列表数据
   */
  const fetchListShippingAddresses = async () => {
    setTrue();
    const [err, res] = await to(UserRequest.ListShippingAddresses({}));
    if (err) {
      setFalse();
      return;
    }
    setList(res.data);
    setFalse();
  };

  /**
   * 前往绑定地址界面
   * @param item
   */
  const handleGotoBindAddress = (item: IListShippingAddressesRes) => {
    const { beeperId, relationBeeperId, linkName, phone, houseNumber, harvestAddressId } = item;
    const conversion = Tools.tencentCoordinateToBaiduCoordinate(item.longitude, item.latitude);
    const message = JSON.stringify({
      lat: conversion.lat,
      lng: conversion.lng,
      address: { province: item.provinceName, city: item.cityName, district: item.areaName, address: item.address },
    });
    navigation.navigate('bindAddress', { id: harvestAddressId, beeperId, relationBeeperId, message, houseNumber, phone, linkName });
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <ScrollView style={[styles.root]} contentContainerStyle={{ alignItems: 'center', paddingBottom: 20 }}>
        {list.map((item, index) => {
          return (
            <React.Fragment key={index}>
              <TouchableOpacity style={styles.list} onPress={() => handleGotoBindAddress(item)}>
                <View>
                  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    {item.beeperId && (
                      <Text highlight fontSize={12} color={'#4988d4'} style={{ backgroundColor: '#E2EEFC', marginRight: 6, height: 22 }}>
                        呼叫器地址
                      </Text>
                    )}
                    <Text fontSize={15} fontWeight={'bold'}>
                      {item.villageName} {item.houseNumber}
                    </Text>
                  </View>
                  <Text fontSize={12} color={'#999999'}>
                    {item.linkName} {item.phone}
                  </Text>
                </View>
                <Text>
                  <AntDesign name={'edit'} style={{ fontSize: 16 }} />
                </Text>
              </TouchableOpacity>
              <Divider bg="#f2f2f2" />
            </React.Fragment>
          );
        })}

        {!loading && list.length === 0 && (
          <View h={560}>
            <Empty text={'暂无收货地址'} />
          </View>
        )}

        {loading && <LoadingSkeleton rows={9} />}

        {!loading && (
          <Button
            onPress={() => navigation.navigate('bindAddress')}
            bg={CommonStyle.mainColor} // Normal button background
            _pressed={{
              bg: CommonStyle.btnSelectMainColor, // Background color when pressed
            }}
            width={'90%'}
            marginTop={'8'}
          >
            添加地址
          </Button>
        )}
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: 'white' },
  list: { paddingVertical: 12, paddingHorizontal: 12, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
});

export default ReceivingAddress;
